<template>
  <div class="container">
    <div class="header">
      <img src="../assets/photo/main/display_history.png" alt="" @click="toggleHistory" class="toggle-button">
      <img src="../assets/photo/main/new_page.png" alt="" @click="addNewRecord" id="add_button">
      <!-- 对话模型 -->
      <el-select v-model="selectedGPT" class="model-selector" @change="handleGPTChange">
        <el-option label="星火模型" value="spark"></el-option>
        <el-option label="智谱清言" value="zhipu"></el-option>
        <el-option label="百川模型" value="baichuan"></el-option>
        <el-option label="自研模型" value="self"></el-option>
      </el-select>
      <!-- 对话方式 -->
      <el-select v-model="selectedModel" class="model-selector" @change="handleModelChange" id="special_style">
        <el-option label="普通对话" value="ordinaryDialogue"></el-option>
        <el-option label="代码生成" value="codeGeneration"></el-option>
        <el-option label="代码解释" value="codeInterpretation"></el-option>
        <el-option label="代码纠错" value="codeCorrection"></el-option>
        <el-option label="单元测试" value="unitTest"></el-option>
      </el-select>
    </div>
    <transition name="slide">
      <HistoryList v-show="historyVisible" :history="history" @select="selectHistory" @clearSelection="clearSelection" @deleteRecord="handleDeleteRecord" style="margin-top: 7vh;" ref="history"/>
    </transition>
    <div class="content-area">
      <ContentDisplay :content="selectedContent" :userName="user_name" ref="chatContainer"/>
      
      <!-- 根据模式动态显示不同的输入框 -->
      <div v-if="selectedModel === 'codeGeneration'" class="input-area" :class="{'has-attachment': attachments.length > 0, 'is-phone-input-area': is_phone}">
        <el-input 
          v-model="functionDescription" 
          placeholder="点击修改函数描述及参数"
          readonly 
          @focus="openDialog"
          style="cursor: pointer;"
        >
          <!-- 提交按钮 -->
          <i slot="prefix" class="el-input__icon el-icon-edit"></i>
        </el-input>
        <el-button type="primary" @click="submitContent" :disabled="loading" style="margin-left: 10px;">
          {{ loading ? '处理中...' : '提交' }}
        </el-button>
      </div>

      <!-- 其他模式下的输入框 -->
      <div v-else>
        <div :class="{ 'is-phone-input-area': is_phone }">
          <div class="input-area" :class="{'has-attachment': attachments.length > 0}">
            <el-input
              type="text"
              placeholder="给GPT发送消息"
              v-model="put_text"
              maxlength="500"
              show-word-limit
            >
              <i slot="prefix" class="el-input__icon el-icon-paperclip" @click="uploadFile"></i>
            </el-input>
            <el-button type="primary" @click="submitContent" :disabled="loading">{{ loading ? '处理中...' : '提交' }}</el-button>
            <input type="file" ref="fileInput" @change="handleFileUpload" style="display: none;" />
          </div>
          <ul class="attachment-list" v-if="attachments.length">
            <li>
              <span>{{ attachments[0].name }}</span>
              <el-button type="text" @click="removeAttachment">移除</el-button>
            </li>
          </ul>
        </div>
      </div>


      <!-- 弹出框内容 -->
      <el-dialog 
        title="编辑函数信息" 
        :visible.sync="dialogVisible"
        @click="dialogVisible = false"
        :close-on-click-modal="false"
        :append-to-body="true"
        id="main_dialog">
        
        <!-- 必填项 -->
        <div class="required-section">
          <div class="section-header">必填项</div>
          <el-input 
            v-model="functionDescription" 
            placeholder="函数描述" 
            maxlength="200" 
            show-word-limit 
            required
            :class="{ 'input-error': !functionDescription }"
          ></el-input>
          <div v-if="!functionDescription" class="error-message">函数描述为必填项</div>
        </div>

        <!-- 选填项 -->
        <div class="optional-section">
          <div class="section-header">选填项</div>
          <el-input v-model="functionName" placeholder="函数名称" maxlength="20" show-word-limit></el-input>

          <!-- 参数列表 -->
          <div v-if="paraList.length > 0" class="param-section" style="margin-top: 18px; border: 1px solid #444; padding: 10px;">
            <div style="text-align: left;">
              <el-button @click="addParam" style="margin-bottom: 8px;" type="primary">添加参数信息</el-button>
            </div>
            <div v-for="(param, index) in paraList" :key="`param-${index}`" class="param-item" style="display: flex; align-items: center; gap: 10px;">
              <el-input v-model="param.var" placeholder="参数名称" style="flex: 1;"></el-input>
              <el-input v-model="param.mean" placeholder="参数描述" style="flex: 1;"></el-input>
              <el-button @click="removeParam(index)" class="remove-param-button" style="flex-shrink: 0;">移除</el-button>
            </div>
          </div>

          <!-- 没有参数时只显示按钮 -->
          <div v-else style="text-align: left;">
            <el-button @click="addParam" style="margin-top: 18px; margin-bottom: 8px;" type="primary">添加参数信息</el-button>
          </div>

          <!-- 返回值类型 -->
          <div v-if="returnList.length > 0" class="return-section" style="margin-top: 18px; border: 1px solid #444; padding: 10px;">
            <div style="text-align: left;">
              <el-button @click="addReturn" style="margin-bottom: 8px;" type="primary">添加返回值信息</el-button>
            </div>
            <div v-for="(ret, index) in returnList" :key="`return-${index}`" class="return-item" style="display: flex; align-items: center; gap: 10px;">
              <el-input v-model="ret.var" placeholder="返回值名称" style="flex: 1;"></el-input>
              <el-input v-model="ret.mean" placeholder="返回值描述" style="flex: 1;"></el-input>
              <el-button @click="removeReturn(index)" class="remove-return-button" style="flex-shrink: 0;">移除</el-button>
            </div>
          </div>

          <!-- 没有返回值时只显示按钮 -->
          <div v-else style="text-align: left;">
            <el-button @click="addReturn" style="margin-top: 18px; margin-bottom: 8px;" type="primary">添加返回值信息</el-button>
          </div>

          <!-- 测试样例 -->
          <div v-if="testCases.length > 0" class="test-case-section" style="margin-top: 18px; border: 1px solid #444; padding: 10px;">
            <div style="text-align: left;">
              <el-button @click="addTestCase" style="margin-bottom: 8px;" type="primary">添加测试样例</el-button>
            </div>
            <div v-for="(testCase, index) in testCases" :key="`test-case-${index}`" class="test-case-item" style="display: flex; align-items: center; gap: 10px;">
              <el-input v-model="testCase.var" placeholder="输入" style="flex: 1;"></el-input>
              <el-input v-model="testCase.mean" placeholder="输出" style="flex: 1;"></el-input>
              <el-button @click="removeTestCase(index)" class="remove-testcase-button" style="flex-shrink: 0;">移除</el-button>
            </div>
          </div>
          
          <!-- 没有测试样例时只显示按钮 -->
          <div v-else style="text-align: left;">
            <el-button @click="addTestCase" style="margin-top: 18px; margin-bottom: 8px;" type="primary">添加测试样例</el-button>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" style="margin-right: 10px;">取消</el-button>
          <el-button 
            type="primary" 
            :disabled="!functionDescription" 
            @click="sureInCodeGeneration">确认</el-button>
        </span>
      </el-dialog>

      <!-- 代码生成结果弹出窗 -->
      <el-dialog 
        :visible.sync="dialogVisible2" 
        title="代码生成"
        :append-to-body="true"
        @click="dialogVisible2 = false"
        :close-on-click-modal="false"
        >
        <div v-html="renderedCode" id="generated-code-block"></div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="copyCode">复制代码</el-button>
        </span>
      </el-dialog>
    </div>
    <el-popover placement="bottom" trigger="click" popper-class="el-popover-self" ref="popover" :append-to-body="false">
      <div class="popover-content-new">
        <el-avatar id="user-avatar" :size="45"> {{user_name}} </el-avatar>
        <div class="name-edit">
          <span id="user-name">{{user_name}}</span>
          <el-button type="text" class="edit-name-button" @click="editUserName">
            <i class="el-icon-edit"></i>
          </el-button>
        </div>
        <div class="popover-actions">
          <el-button type="text" class="popover-item-new" @click="changeUserData">
            <img src="../assets/photo/main/edit_user.png" alt="" class="user_img_new">
            <span class="user_word_new">修改密码</span>
          </el-button>
          <el-button type="text" class="popover-item-new" @click="handleLogout">
            <img src="../assets/photo/main/exit_user.png" alt="" class="user_img_new">
            <span class="user_word_new">退出登录</span>
          </el-button>
        </div>
      </div>
      <el-avatar id="user" slot="reference"> {{user_name}} </el-avatar>
    </el-popover>
  </div>
</template>

<script>
import HistoryList from '@/components/HistoryList.vue';
import ContentDisplay from '@/components/ContentDisplay.vue';
import { addChat } from '@/api/main/newSession';
import { getChatList } from '@/api/main/getChatIdList';
import { getChatContent } from '@/api/main/getChatContent';
import { updateUserName } from '@/api/edit/changeUserInfo';
import { updateTheme } from '@/api/main/updateTheme';
import {getCodeGeneration} from '@/api/main/codeGeneration';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';

export default {
  name: 'Main',
  components: {
    HistoryList,
    ContentDisplay,
  },
  data() {
    return {
      dialogVisible: false, // 控制弹窗可见性
      functionDescription: '', // 函数描述
      functionName: '', // 函数名称
      paraList: [], // 参数列表
      returnList: [], // 初始状态为空
      testCases: [], // 测试样例
      history: [],  // 历史记录
      selectedContent: [], // 初始化为空数组
      selectedChatId: null, // 当前选择的chatid
      historyVisible: true,
      user_name: '',
      put_text: '',  // 发送的文本（目前限500字）
      attachments: [], // 存储上传的附件
      selectedModel: 'ordinaryDialogue', // 默认选择普通对话
      selectedGPT: 'spark', // 默认选择星火大模型
      chooseModel: {
        "ordinaryDialogue": "普通对话",
        "codeGeneration": "代码生成",
        "codeInterpretation": "代码解释",
        "codeCorrection": "代码纠错",
        "unitTest": "单元测试"
      },
      chooseGPT: {
        "spark": "星火模型",
        "zhipu": "智谱清言",
        "baichuan": "百川模型",
        "self": "自研模型"
      },
      user_id: '',   // 用户id,用于后续一切操作
      loading: false, // 用于显示加载状态
      is_phone: false, // 用于判断是否是手机端
      dialogVisible2: false,  // 代码生成弹窗
      generatedCode: '',   // 代码生成生成的代码
      renderedCode: ''    // 代码生成渲染的代码
    };
  },
  created() {
    this.getUserName();   // 用户信息初始化
    this.initializeChatList();  // 用户的所有聊天chatid初始化
    this.is_phone = /mobile|tablet|ip(hone|od|ad)|android/i.test(navigator.userAgent);  // 检测是否为手机端  
  },
  methods: {
    // 打开弹窗
    openDialog() {
      this.dialogVisible = true;
    },

    // 添加新的参数项
    addParam() {
      this.paraList.push({ "var": '', "mean": '' });
    },

    // 移除指定的参数项
    removeParam(index) {
      this.paraList.splice(index, 1);
    },

    addReturn() {
      this.returnList.push({ "var": '', "mean": '' }); // 添加返回值组
    },
    removeReturn(index) {
      this.returnList.splice(index, 1);
    },

    // 添加新的测试用例
    addTestCase() {
      // 最多添加3个
      if (this.testCases.length >= 3) {
        this.$message.warning('最多添加3个测试用例');
        return;
      }
      // var--->输入, mean--->输出    (方便后端统一处理)
      this.testCases.push({ "var": '', "mean": '' });
    },

    // 移除指定的测试用例
    removeTestCase(index) {
      this.testCases.splice(index, 1);
    },

    // 获取用户信息
    getUserName() {
      this.user_name = localStorage.getItem('auto_log_people');
      const userInfo = JSON.parse(localStorage.getItem(this.user_name));
      if (userInfo) {
        const { accountName, user_id } = userInfo;
        this.user_name = accountName;
        this.user_id = user_id;
      }
    },

    sureInCodeGeneration() {
      // 判断 paraList、returnList、testCases 是否存在空值
      let flag = true;

      this.paraList.forEach((item, index) => {
        if (!item.var || !item.mean) {
          this.$message.error(`参数${index + 1}的名称和描述不能为空`);
          flag = false;
        }
      });

      this.returnList.forEach((item, index) => {
        if (!item.var || !item.mean) {
          this.$message.error(`返回值${index + 1}的名称和描述不能为空`);
          flag = false;
        }
      });

      this.testCases.forEach((item, index) => {
        if (!item.var || !item.mean) {
          this.$message.error(`测试样例${index + 1}的输入和输出不能为空`);
          flag = false;
        }
      });

      if (flag) {
        // 只有在所有校验通过的情况下才关闭对话框
        this.dialogVisible = false;
      }
    },


    // 初始化chatid
    async initializeChatList() {
      const response = await getChatList(this.user_id);
      if (response.status === "200") {
        if (Array.isArray(response.data.chat_ilst) && response.data.chat_ilst.length > 0) {
          this.history = response.data.chat_ilst.map(chat => ({
            title: chat.theme,
            content: [],
            chatid: chat.chatId,
          }));
        } else {
          this.history = []; // 没有会话时设置为空数组
          this.$message({
            message: '没有会话记录',
            type: 'info'
          });
        }
      } else {
        this.$message({
          message: '获取会话列表失败',
          type: 'error'
        });
      }
    },

    // 选择历史记录
    async selectHistory(record) {
      this.selectedChatId = record.chatid; // 记录当前选择的chatid
      const response = await getChatContent(record.chatid);
      if (response.status === "200") {
        this.selectedContent = (response.data.chat_content || []).map(message => ({
          role: message.role,
          content: message.content
        }));
        this.$nextTick(() => {
          this.$refs.chatContainer.scrollToBottomIfNeeded();
        });
      } else {
        this.$message({
          message: '获取会话内容失败',
          type: 'error'
        });
      }
    },

    // 添加新记录
    addHistory(newRecord) {
      this.history.push(newRecord);
    },

    // 删除记录
    async handleDeleteRecord() {
      this.clearSelection(); // 调用清除选中记录的方法
    },

    // 清除选中的记录
    clearSelection() {
      this.selectedChatId = null;
      this.selectedContent = [];
    },

    // 切换历史记录是否显示
    toggleHistory() {
      this.historyVisible = !this.historyVisible;
    },

    // 注销
    handleLogout() {
      this.$confirm('此操作将注销账户,在重新登录之前无法使用本产品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('loginTime');
        localStorage.removeItem('auto_log_people');
        this.$isLoggedIn = false; // 更新 Vue 实例的登录状态
        this.$router.push({ name: 'login' });
        this.$message({
          type: 'success',
          message: '注销成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消注销'
        });
      });
    },

    // 添加新记录(实则将高亮记录置为null)
    addNewRecord() {
      this.selectedChatId = null; // 取消选中的记录
      this.selectedContent = []; // 清空当前内容
      this.$refs.history.clearSelection(); // 取消高亮
      // 强制关闭返回底部按钮
      this.$refs.history.data.showScrollButton = false;
    },

    // 修改用户密码
    changeUserData() {
      this.$router.push({ name: 'edit' });
    },

    // 上传附件
    uploadFile() {
      if (this.attachments.length === 0) {
        this.$refs.fileInput.click();
      } else {
        this.$message.error('一次只能上传一个文件');
      }
    },

    // 检测上传文件
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (file && file.type === "text/plain") {
        this.attachments = [file]; // 只存储一个文件
        event.target.value = ''; // 清空文件输入，使得可以重复上传相同文件
      } else {
        this.$message.error('只能上传txt文件');
      }
    },
    // 读取文件内容
    async readFileContent(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = reject;
        reader.readAsText(file);
      });
    },

    // 移除附件
    removeAttachment() {
      this.attachments = [];
    },

    // 提交问题，获取回复
    async submitContent() {
      // 判断是否为空--->非代码生成模式
      if (this.put_text.trim() === '' && this.selectedModel!=="codeGeneration") {
          this.$message.error('内容不能为空');
          return;
      }

      this.loading = true; // 开始加载状态

      // 判断会话func
      if(this.selectedModel!=="codeGeneration"){
        if (!this.selectedChatId) {
          // 创建新会话
          const chatCreated = await this.createNewChat();
          // 更新记录名字到数据库
          try {
            await updateTheme(this.selectedChatId, this.put_text.length > 8 ? `${this.put_text.slice(0, 8)}...` : `${this.put_text}`);
          } catch (error) {
            console.error("Failed to update theme:", error);
            this.$message.error("主题更新失败，请重试");
          }
          if (!chatCreated) {
              this.$message.error('创建新会话失败');
              this.loading = false;
              return;
          }
        }

        let fileContent = '';
        let fileName = '';
        if (this.attachments.length > 0) {
          fileContent = await this.readFileContent(this.attachments[0]);
          fileName = this.attachments[0].name;
          // console.log(fileContent);
          // console.log(fileName);
        }

        // 发送用户消息到界面上
        const userMessage = { role: 'user', content: this.put_text, fileContent: fileContent, fileName: fileName };
        this.selectedContent.push(userMessage);
      

        // 插入一条等待填充内容的assistant消息
        let gptMessage = { role: 'assistant', content: '' };
        this.selectedContent.push(gptMessage);
        let lastIndex = this.selectedContent.length - 1;
      
        let func = 0;
        switch (this.selectedModel) {
          case "ordinaryDialogue":
            func = "1";
            break;
          case "codeInterpretation":
            func = "2";
            break;
          case "codeCorrection":
            func = "3";
            break;
          case "unitTest":
            func = "4";
            break;
          default:
            func = "1";
        }

        // 124.221.156.242:8081

        try {
          const response = await fetch('http://124.221.156.242:8081/chat/sendStreamMessage', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              messages: this.put_text.trim(),
              chatId: this.selectedChatId,
              userId: this.user_id,
              func: func,
              file: fileContent,
              isFirst: "True",
              llmName: this.selectedGPT
            })
          });

          if (!response.ok) {
            throw new Error('Network response was not ok');
          }

          let reader = response.body.getReader();
          let decoder = new TextDecoder("utf-8");

          while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            let partialResult = decoder.decode(value, { stream: true });

            for (let i = 0; i < partialResult.length; i++) {
              this.selectedContent[lastIndex].content += partialResult[i];
              await this.sleep(30); // 控制字符显示的速度
              this.$refs.chatContainer.scrollToBottomIfNeeded(); // 检查是否需要滚动到底部
            }
          }
        } catch (error) {
          console.error('Error:', error);
          this.selectedContent[lastIndex].content = '检测到网络不给力，请重新尝试';
        } finally {
            this.loading = false;
            this.put_text = '';
            this.attachments = [];
        }
      }else{
        // 代码生成特殊处理
        if(this.functionDescription.trim() === ''){
          this.$message.error('内容不能为空');
          this.loading = false;
          return;
        }

        try {
          const response = await getCodeGeneration(this.functionDescription, this.functionName, this.paraList, this.testCases, this.returnList, this.selectedGPT);
          let res = response.data.code;

          // 移除开头和结尾的 ``` 和语言标记
          const codeContent = res.replace(/(^```[a-z]*\s*)|(\s*```$)/g, '');

          this.generatedCode = codeContent;

          // 自动高亮处理
          this.renderedCode = hljs.highlightAuto(codeContent).value;

          this.dialogVisible2 = true; // 打开弹窗
        } catch (error) {
          console.error('Error:', error);
          this.generatedCode = "生成代码失败";
          let codeContent = "生成代码失败";
          // 自动高亮处理
          this.renderedCode = hljs.highlightAuto(codeContent).value;
          this.dialogVisible2 = true; // 打开弹窗
        } finally {
          this.loading = false;
          this.put_text = '';
          this.functionDescription = '';
          this.functionName = '';
          this.paraList = [];
          this.returnList = [];
          this.testCases = [];
          this.attachments = [];
        }
      }
    },

    // 复制代码生成的代码
    copyCode() {
      // 使用原生 JavaScript 实现复制功能
      const textarea = document.createElement('textarea');
      textarea.value = this.generatedCode;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        document.execCommand('copy');
        this.$message.success('代码已复制到剪贴板');
      } catch (err) {
        this.$message.error('复制失败');
      }
      document.body.removeChild(textarea);
    },

    // 用于控制打字速度的辅助函数
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    },

    // 创建新会话
    async createNewChat() {
      const response = await addChat(this.user_id, "新会话");
      if (response.status === "200") {
        const chatid = response.data.chat_id;
        const newRecord = {
          title: this.put_text.length > 8 ? `${this.put_text.slice(0, 8)}...` : `${this.put_text}`,
          content: [],
          chatid: chatid,
        };
        this.history.unshift(newRecord);
        this.selectedChatId = chatid;
        this.selectedContent = []; // 清空当前内容
        this.$nextTick(async () => {
          this.$refs.history.select(newRecord, 0); // 选中并高亮新创建的会话
        });
        return true;
      }
      return false;
    },

    // 切换模式
    handleModelChange() {
      this.$message({
        message: `已切换到${this.chooseModel[this.selectedModel]}`,
        type: 'success'
      });
    },

    // 切换GPT
    handleGPTChange() {
      this.$message({
        message: `已切换到${this.chooseGPT[this.selectedGPT]}`,
        type: 'success'
      });
    },

    // 编辑用户名
    async editUserName() {
      this.$prompt('编辑用户名:', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '新用户名不能为空'
      }).then(async({ value }) => {
        if (value.trim() === '') {
          this.$message({
            message: '新用户名不能为空或空格',
            type: 'warning'
          });
          return;
        }
        if (value === this.user_name) {
          this.$message({
            message: '新用户名不能与旧用户名相同',
            type: 'warning'
          });
          return;
        }
        const account = localStorage.getItem('auto_log_people');
        const userInfo = JSON.parse(localStorage.getItem(account));
        const { user_id } = userInfo;
        
        const getData = await updateUserName(user_id, value); 
        if (getData.status === 200) {
          localStorage.removeItem(account);
          localStorage.setItem(account, JSON.stringify({ accountName: value, user_id: user_id }));
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.user_name = value;
        } else {
          this.$message({
            message: '修改失败',
            type: 'error'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        });
      });
      
      // 设置聚焦
      this.$nextTick(() => {
        const inputBox = document.querySelector('.el-message-box__input');
        if (inputBox) {
          inputBox.focus();
        }
      });
    }
  },
  mounted() {
    this.getUserName();
  }
};
</script>

<style>
html, body, #app {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  overflow: hidden; /* 禁止滚动 */
}

.container {
  display: flex;
  height: 90vh;
  position: relative;
}

.content-area {
  height: 96vh !important;  
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  z-index: 10;
}

.toggle-button {
  width: 3vw;
  height: auto;
  z-index: 999;
  margin-top: .5vh;
  margin-left: .5vw;
  cursor: pointer;
}

#add_button {
  width: 3.3vw;
  height: auto;
  cursor: pointer;
  margin-left: 6vw;
  margin-top: .5vh;
}

.model-selector {
  margin-left: 2vw;
  margin-top: 1vh;
}

.model-selector .el-input__inner:hover {
  background-color: #eee;
}

.model-selector .el-input__inner {
  border: none !important;
  width: 13vw;
  font-size: 1.8vw;
  font-weight: bolder;
}

.history-list {
  width: 13%;
  height: 100vh;
  overflow-y: auto;
  border-right: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 87%;
  padding: 20px;
  overflow-y: auto;
}

.content-display {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.input-area {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.input-area .el-input {
  flex: 1;
}

.input-area .el-button {
  margin-left: 10px;
}

.input-area .el-input__icon {
  cursor: pointer;
}

.input-area.has-attachment {
  margin-bottom: 0 !important;
}

.is-phone-input-area {
  margin-bottom: 80px !important;
}

/* 过渡效果 */
.slide-enter-active, .slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter, .slide-leave-to {
  transform: translateX(-100%);
}

#user {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 11;
}

.el-avatar {
  background-color: #6B92DA !important;
  cursor: pointer;
}

.popover-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.popover-content-new {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200px;
  padding: 20px;
}

#user-avatar {
  margin-top: 6px;
  margin-bottom: 10px;
}

.name-edit {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

#user-name {
  font-size: 1.5vw;
  font-weight: bold;
  margin-right: 5px;
}

.edit-name-button {
  margin-right: 10px;
  font-size: 1.5vw !important;
}

.edit-name-button:hover {
  background-color: white !important;
}

.popover-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.popover-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.popover-item-new {
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-popover-self {
  width: auto !important;
  min-width: 200px !important;
  padding: 0;
}

.el-popover {
  padding: 0 !important;
}

.el-popper[x-placement^=bottom] {
  margin-top: 5px !important;
}

.user_img {
  width: 2vw;
  height: auto;
  margin-right: .6vw;
  cursor: pointer;
}

.user_img_new {
  width: 20px;
  height: auto;
  margin-right: 5px;
  cursor: pointer;
}

.user_word {
  font-size: 1.5vw;
  position: relative;
  top: -.5vh;
}

.user_word_new {
  font-size: 14px;
  position: relative;
  top: -.2vh;
}

.attachment-list {
  margin-top: 10px;
  list-style: none;
  padding: 0;
}

.attachment-list li {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.attachment-list span {
  max-width: 80%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.required-section {
  border: 1px solid #409EFF;
  padding: 10px;
  margin-bottom: 20px;
}

.optional-section {
  border: 1px solid #444;
  padding: 10px;
}

.section-header {
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.param-section, .test-case-section, .return-section {
  margin-top: 18px;
  border: 1px solid #444;
  padding: 10px;
}

.param-item, .test-case-item, .return-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.remove-param-button, .remove-testcase-button, .remove-return-button {
  flex-shrink: 0;
}

.input-error {
  border-color: red;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

#generated-code-block {
  white-space: pre;  
  text-align: left;
  font-family: "Courier New", Courier, monospace;
  background-color: beige;
  border: #444 solid 1px;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto; 
  overflow-y: auto;
  line-height: 1.5;
  width: 100%;  
  max-height: 500px; 
  box-sizing: border-box; 
}




@media (max-width: 768px) {
  .container {
    height: 90vh;
  }

  .history-list {
    width: 30%;
  }

  .toggle-button {
    width: 8.5%;
    height: auto;
    z-index: 999;
    margin-top: .5vh;
    margin-left: .5vw;
    cursor: pointer;
  }

  #add_button {
    width: 9vw;
    height: auto;
    cursor: pointer;
    margin-left: 11vw;
  }

  .model-selector {
    margin-left: 2vw;
  }

  .model-selector .el-input__inner:hover {
    background-color: #eee;
  }

  #special_style {
    margin-left: -1.3vh;
  }

  .model-selector .el-input__inner {
    border: none !important;
    width: 28vw;
    font-size: 4vw;
    font-weight: bolder;
  }

  .el-popover-self {
    width: auto !important;
    min-width: 120px !important;
    padding: 0;
  }

  .popover-content-new {
    padding: 10px;
  }

  #user-avatar {
    margin-bottom: 10px;
  }

  #user-name {
    font-size: 5vw;
    font-weight: bold;
    margin-right: 5px;
  }

  .edit-name-button {
    margin-right: 10px;
    font-size: 5vw !important;
  }

  .name-edit {
    margin-bottom: 10px;
  }

  .edit-name-button {
    margin-right: 5px;
  }

  .popover-actions {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .popover-item-new {
    margin-bottom: 0;
  }

  .user_img {
    width: 5vw;
  }

  .user_img_new {
    width: 24px;
  }

  .user_word {
    font-size: 4vw;
    position: relative;
    top: -.5vh;
  }

  .user_word_new {
    font-size: 16px;
  }
  .el-dialog{
    z-index: 9999 !important;
    width: 90% !important; 
    max-width: 90%;
  }


}
</style>
